package com.love.cloud.admin.service.impl;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.love.cloud.admin.api.dto.UserDTO;
import com.love.cloud.admin.api.entity.SysUser;
import com.love.cloud.admin.api.entity.SysUserGroup;
import com.love.cloud.admin.api.entity.SysUserGroupMember;
import com.love.cloud.admin.api.entity.SysUserRole;
import com.love.cloud.admin.api.vo.GroupMemberRoleVo;
import com.love.cloud.admin.api.vo.MobilizeVo;
import com.love.cloud.admin.api.vo.SysUserGroupPageVo;
import com.love.cloud.admin.api.vo.UserVO;
import com.love.cloud.admin.mapper.SysUserGroupMapper;
import com.love.cloud.admin.mapper.SysUserGroupMemberMapper;
import com.love.cloud.admin.mapper.SysUserMapper;
import com.love.cloud.admin.mapper.SysUserRoleMapper;
import com.love.cloud.admin.service.SysUserGroupService;
import com.love.cloud.common.core.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hongdongqu
 */
@Service
public class SysUserGroupServiceImpl extends ServiceImpl<SysUserGroupMapper, SysUserGroup> implements SysUserGroupService {
    @Resource
    private SysUserGroupMemberMapper sysUserGroupMemberMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;


    @Override
    public Object update(SysUserGroup sysUserGroup) {
        if(StringUtils.isNotEmpty(sysUserGroup.getName())){
            sysUserGroup.setFirstSpell(PinyinUtil.getFirstLetter(sysUserGroup.getName(),""));
            sysUserGroup.setSpell(PinyinUtil.getPinyin(sysUserGroup.getName(),""));
        }
        return this.updateById(sysUserGroup);
    }

    @Override
    public Object add(SysUserGroup sysUserGroup) {
        if(StringUtils.isNotEmpty(sysUserGroup.getName())){
            sysUserGroup.setFirstSpell(PinyinUtil.getFirstLetter(sysUserGroup.getName(),""));
            sysUserGroup.setSpell(PinyinUtil.getPinyin(sysUserGroup.getName(),""));
        }
        return this.save(sysUserGroup);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object delete(Long id) {
        //删除掉组的数据
        this.removeById(id);
        //删除组内的成员
        QueryWrapper<SysUserGroupMember> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserGroupMember::getGroupId,id);
        return sysUserGroupMemberMapper.delete(queryWrapper);
    }

    @Override
    public Object groupMemberPage(Page page, SysUserGroupPageVo sysUserGroupPageVo) {
        QueryWrapper<SysUserGroupMember> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserGroupMember::getGroupId,sysUserGroupPageVo.getGroupId());
        Page<SysUserGroupMember> pageInfo=sysUserGroupMemberMapper.selectPage(page,queryWrapper);
        for (SysUserGroupMember sysUserGroupMember:pageInfo.getRecords()) {
            UserDTO userDTO=new UserDTO();
            userDTO.setId(sysUserGroupMember.getUserId());
            List<UserVO> userVosList = sysUserMapper.getUserVosList(userDTO);
            if(userVosList!=null&&userVosList.size()>0){
                sysUserGroupMember.setUserVos(userVosList.get(0));
            }
        }
        return pageInfo;
    }

    @Override
    public Object getList() {
        QueryWrapper<SysUserGroup> queryWrapper =new QueryWrapper<>();
        return this.list(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object mobilize(MobilizeVo mobilizeVo) {
        //清空原来的数据
        QueryWrapper<SysUserGroupMember> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserGroupMember::getGroupId,mobilizeVo.getGroupId());
        //直接物理删除
        sysUserGroupMemberMapper.deletePhysicsById(queryWrapper);
        if(mobilizeVo.getSysUserGroupMemberList()!=null){
            for (Map<String,Object> userMap :mobilizeVo.getSysUserGroupMemberList()) {
                Long userId=userMap.get("userId")!=null?Long.valueOf(userMap.get("userId").toString()):null;
                Long deptId=userMap.get("deptId")!=null?Long.valueOf(userMap.get("deptId").toString()):null;
                if(userId!=null){
                    SysUserGroupMember sysUserGroupMember=new SysUserGroupMember();
                    sysUserGroupMember.setGroupId(mobilizeVo.getGroupId());
                    sysUserGroupMember.setUserId(userId);
                    sysUserGroupMember.setDeptId(deptId);
                    sysUserGroupMemberMapper.insert(sysUserGroupMember);
                }
            }
        }
        return true;
    }

    @Override
    public Object removeGroupMember(SysUserGroupMember sysUserGroupMember) {
        //直接物理删除对应的成员
        if(sysUserGroupMember.getId()==null){
            throw new BusinessException("请传入对应的id");
        }
        QueryWrapper<SysUserGroupMember> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserGroupMember::getId,sysUserGroupMember.getId());
        sysUserGroupMemberMapper.deletePhysicsById(queryWrapper);
        return true;
    }

    @Override
    public Object getAllGroupMember(SysUserGroupMember sysUserGroupMember) {
        if(sysUserGroupMember.getGroupId()==null){
            throw new BusinessException("请传入用户组的id");
        }
        QueryWrapper<SysUserGroupMember> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserGroupMember::getGroupId,sysUserGroupMember.getGroupId())
                .select(SysUserGroupMember::getUserId,SysUserGroupMember::getDeptId);
        List<SysUserGroupMember> sysUserGroupMembers=sysUserGroupMemberMapper.selectList(queryWrapper);
        List<Map<String,Object>> resultList=new ArrayList<>();
        //组装回显的id
        for (SysUserGroupMember item:sysUserGroupMembers) {
            Map<String,Object> map=new HashMap<>();
            map.put("userId",item.getUserId());
            map.put("deptId",item.getDeptId());
            map.put("id",item.getUserId()+"_"+item.getDeptId());
            //查询用户信息
            SysUser sysUser = sysUserMapper.selectById(item.getUserId());
            if(sysUser!=null){
                map.put("name",sysUser.getName());
            }
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object setGroupMemberRole(GroupMemberRoleVo groupMemberRoleVo) {
        //获取组中的的成员
        QueryWrapper<SysUserGroupMember> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserGroupMember::getGroupId,groupMemberRoleVo.getRole());
        List<SysUserGroupMember> sysUserGroupMembers = sysUserGroupMemberMapper.selectList(queryWrapper);
        for (SysUserGroupMember sysUserGroupMember:sysUserGroupMembers) {
            if(sysUserGroupMember.getUserId()!=null){
                //查询是否包含了角色
                for (Long roleId :groupMemberRoleVo.getRole()) {
                    QueryWrapper<SysUserRole> sysUserRoleQueryWrapper=new QueryWrapper<>();
                    sysUserRoleQueryWrapper.lambda().eq(SysUserRole::getUserId,sysUserGroupMember.getUserId())
                            .eq(SysUserRole::getRoleId,roleId);
                    SysUserRole sysUserRole = sysUserRoleMapper.selectOne(sysUserRoleQueryWrapper);
                    if(sysUserRole!=null){
                        continue;
                    }
                    sysUserRole=new SysUserRole();
                    sysUserRole.setRoleId(roleId);
                    sysUserRole.setUserId(sysUserGroupMember.getUserId());
                    sysUserRoleMapper.insert(sysUserRole);
                }
            }
        }
        return true;
    }
}
